from django.db import models
from django.contrib.auth import get_user_model

User = get_user_model()


class AdSpace(models.Model):
    """广告位"""
    POSITION_CHOICES = [
        ('homepage_banner', '首页轮播'),
        ('homepage_recommend', '首页推荐'),
        ('category_sidebar', '分类侧边栏'),
        ('book_detail', '图书详情页'),
        ('search_result', '搜索结果页'),
        ('checkout_page', '结算页面'),
    ]

    name = models.CharField(max_length=100, verbose_name='广告位名称')
    position = models.CharField(max_length=50, choices=POSITION_CHOICES, unique=True, verbose_name='广告位置')
    description = models.TextField(blank=True, verbose_name='位置描述')
    
    # 尺寸信息
    width = models.IntegerField(verbose_name='宽度(px)')
    height = models.IntegerField(verbose_name='高度(px)')
    
    # 价格信息
    base_price = models.DecimalField(max_digits=10, decimal_places=2, verbose_name='基础价格(元/天)')
    discount_rate = models.DecimalField(max_digits=5, decimal_places=4, default=1.0, verbose_name='折扣率')
    
    # 状态
    is_active = models.BooleanField(default=True, verbose_name='是否启用')
    
    # 限制
    max_ads = models.IntegerField(default=5, verbose_name='最大广告数量')
    
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        db_table = 'ad_spaces'
        verbose_name = '广告位'
        verbose_name_plural = '广告位'
        ordering = ['position']

    def __str__(self):
        return self.name


class Advertisement(models.Model):
    """广告"""
    STATUS_CHOICES = [
        ('draft', '草稿'),
        ('pending', '待审核'),
        ('approved', '已通过'),
        ('rejected', '已拒绝'),
        ('active', '已投放'),
        ('paused', '已暂停'),
        ('expired', '已过期'),
    ]

    title = models.CharField(max_length=200, verbose_name='广告标题')
    description = models.TextField(blank=True, verbose_name='广告描述')
    
    # 关联信息
    ad_space = models.ForeignKey(AdSpace, on_delete=models.CASCADE, related_name='advertisements')
    advertiser = models.ForeignKey(User, on_delete=models.CASCADE, related_name='advertisements')
    
    # 广告内容
    image = models.ImageField(upload_to='advertisements/', verbose_name='广告图片')
    link_url = models.URLField(verbose_name='跳转链接')
    alt_text = models.CharField(max_length=200, blank=True, verbose_name='替代文本')
    
    # 投放时间
    start_date = models.DateField(verbose_name='开始日期')
    end_date = models.DateField(verbose_name='结束日期')
    
    # 状态
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='draft', verbose_name='状态')
    
    # 审核信息
    reviewed_by = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True, related_name='reviewed_ads')
    reviewed_at = models.DateTimeField(null=True, blank=True, verbose_name='审核时间')
    review_note = models.TextField(blank=True, verbose_name='审核意见')
    
    # 优先级
    priority = models.IntegerField(default=0, verbose_name='优先级')
    
    # 统计信息
    view_count = models.IntegerField(default=0, verbose_name='展示次数')
    click_count = models.IntegerField(default=0, verbose_name='点击次数')
    click_through_rate = models.FloatField(default=0.0, verbose_name='点击率')
    
    # 预算
    daily_budget = models.DecimalField(max_digits=10, decimal_places=2, default=0, verbose_name='日预算')
    total_budget = models.DecimalField(max_digits=10, decimal_places=2, default=0, verbose_name='总预算')
    spent_amount = models.DecimalField(max_digits=10, decimal_places=2, default=0, verbose_name='已花费金额')
    
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        db_table = 'advertisements'
        verbose_name = '广告'
        verbose_name_plural = '广告'
        ordering = ['-priority', '-created_at']

    def __str__(self):
        return self.title


class AdClick(models.Model):
    """广告点击记录"""
    advertisement = models.ForeignKey(Advertisement, on_delete=models.CASCADE, related_name='clicks')
    user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True, related_name='ad_clicks')
    
    # 点击信息
    ip_address = models.GenericIPAddressField(null=True, blank=True)
    user_agent = models.TextField(blank=True)
    referrer = models.URLField(blank=True)
    
    # 位置信息
    position_x = models.IntegerField(null=True, blank=True)
    position_y = models.IntegerField(null=True, blank=True)
    
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = 'ad_clicks'
        verbose_name = '广告点击'
        verbose_name_plural = '广告点击'
        ordering = ['-created_at']

    def __str__(self):
        return f"{self.advertisement.title} - 点击"


class AdImpression(models.Model):
    """广告展示记录"""
    advertisement = models.ForeignKey(Advertisement, on_delete=models.CASCADE, related_name='impressions')
    user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True, related_name='ad_impressions')
    
    # 展示信息
    ip_address = models.GenericIPAddressField(null=True, blank=True)
    user_agent = models.TextField(blank=True)
    
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = 'ad_impressions'
        verbose_name = '广告展示'
        verbose_name_plural = '广告展示'
        ordering = ['-created_at']

    def __str__(self):
        return f"{self.advertisement.title} - 展示"


class AdCampaign(models.Model):
    """广告活动"""
    STATUS_CHOICES = [
        ('draft', '草稿'),
        ('active', '进行中'),
        ('paused', '已暂停'),
        ('completed', '已完成'),
        ('cancelled', '已取消'),
    ]

    name = models.CharField(max_length=200, verbose_name='活动名称')
    description = models.TextField(blank=True, verbose_name='活动描述')
    
    # 关联用户
    advertiser = models.ForeignKey(User, on_delete=models.CASCADE, related_name='ad_campaigns')
    
    # 时间设置
    start_date = models.DateField(verbose_name='开始日期')
    end_date = models.DateField(verbose_name='结束日期')
    
    # 预算设置
    total_budget = models.DecimalField(max_digits=10, decimal_places=2, verbose_name='总预算')
    daily_budget = models.DecimalField(max_digits=10, decimal_places=2, verbose_name='日预算')
    
    # 状态
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='draft', verbose_name='状态')
    
    # 统计
    total_impressions = models.IntegerField(default=0, verbose_name='总展示量')
    total_clicks = models.IntegerField(default=0, verbose_name='总点击量')
    total_spent = models.DecimalField(max_digits=10, decimal_places=2, default=0, verbose_name='总花费')
    
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        db_table = 'ad_campaigns'
        verbose_name = '广告活动'
        verbose_name_plural = '广告活动'
        ordering = ['-created_at']

    def __str__(self):
        return self.name


class AdPricing(models.Model):
    """广告定价"""
    ad_space = models.ForeignKey(AdSpace, on_delete=models.CASCADE, related_name='pricing')
    
    # 定价策略
    price_type = models.CharField(max_length=20, choices=[
        ('fixed', '固定价格'),
        ('cpm', 'CPM'),
        ('cpc', 'CPC'),
        ('cpd', 'CPD'),
    ], default='fixed', verbose_name='定价类型')
    
    base_price = models.DecimalField(max_digits=10, decimal_places=2, verbose_name='基础价格')
    
    # 时段定价
    peak_multiplier = models.DecimalField(max_digits=5, decimal_places=2, default=1.0, verbose_name='高峰时段倍数')
    off_peak_multiplier = models.DecimalField(max_digits=5, decimal_places=2, default=0.8, verbose_name='低谷时段倍数')
    
    # 有效期
    valid_from = models.DateField(verbose_name='有效开始日期')
    valid_to = models.DateField(verbose_name='有效结束日期')
    
    is_active = models.BooleanField(default=True, verbose_name='是否启用')
    
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        db_table = 'ad_pricing'
        verbose_name = '广告定价'
        verbose_name_plural = '广告定价'
        ordering = ['-created_at']

    def __str__(self):
        return f"{self.ad_space.name} - {self.price_type}"
